<template>
  <infiniteloading
    :is-loading="loadingStatus == 'LOADING' ? true : false"
    :has-more="loadingStatus == 'NO_MORE_DATA' || loadingStatus == 'NO_DATA' ? false : true"
    :is-show-mod="true"
    :use-window="true"
    :isShowBottomTips="false"
    @loadmore="loadMoreList"
  >
    <div class="c-bg-sgray">
      <div class="c-bg-white c-ph24 c-pv30 c-flex-row">
        <div class="top-plan-img"></div>
        <div class="c-flex-column c-justify-center">
          <p class="c-fs30 c-fw600 c-fc-xblack">{{planTypeInfo.coursePlanName}}</p>
          <p class="c-fs20 c-fc-sblack c-mt20">{{planList.length}}个课程</p>
        </div>
      </div>
      <div v-if="planList.length" class="c-flex-row c-justify-sb c-aligni-center c-mh24 c-pv24">
        <div @click="openCatalog"><span class="c-fc-xblack c-fs22">选择课程</span> <i class="iconfont c-fw600 c-fs22">&#xe6a9;</i></div>
        <div @click="switCatalogSort" class="c-fs22 c-fc-xblack c-flex-row c-aligni-center">
          <i class="iconfont c-fs22 c-mr10 time-rotate" :class="{'up':sortType==1}">&#xe8c8;</i>{{sortType==1 ? '时间正序':'时间倒序'}}
        </div>
      </div>

      <div v-for="(item,index) in planList" :key="index" class="c-bg-white c-br20 c-ph20 c-pv20 c-mh24 c-mb24">
        <div @click="toggleSlide(index)" class="c-flex-row c-aligni-center">
          <i class="iconfont c-fc-black c-mr20 c-fs22 arrow-rotate" :class="item.isExpand ? 'expand':''">&#xe8ed;</i>
          <span class="c-fc-xblack c-fs30">{{item.planName}}</span>
        </div>
        <div v-show="item.isExpand" class="c-pl40 c-pt10">
          <div class="c-flex-row c-aligni-center">
            <div class="everytask-progress c-flex-row c-aligni-center">
              <span class="lab">{{item.count}}任务</span>
              <div class="progress">
                <div class="percent theme-bg" :style="{width:item.progress * 100 +'%'}"></div>
              </div>
              <span class="c-ml10 c-fs20 c-fc-gray">{{item.progressPercent}}%</span>
            </div>
          </div>
          <ul class="c-liststyle-none c-mt10">
            <li v-for="(prodItem, index) in item.prodlist" :key="index" @click="jumpToDetail(prodItem)" class="c-flex-row c-aligni-center c-pv20">
              <span
                class="c-flex-shrink0 c-flex-row c-justify-center c-aligni-center c-fs20 c-ww56 c-hh32 c-fw500 c-fc-gray c-bd1 c-br16 c-mr10">{{prodItem.relType== 500 ? '打卡':prodTypes[prodItem.relType]}}</span>
              <div class="c-fs24 c-fc-xblack c-flex-1 c-text-ellipsis1">{{prodItem.relName}}</div>
              <div class="c-flex-shrink0 schedule c-ml24">
                <div v-if="prodItem.prodProgress == 1" class="schedule-complete theme-bg-10"><i class="iconfont c-fs22 theme-fc c-fw600 tick-icon">&#xe6ea;</i></div>
                <template v-else>
                  <div class="schedule-bg"></div>
                  <div class="schedule-percent">
                    <div class="content left">
                      <div class="circle left-circle" :style="'transform:rotate('+`${prodItem.leftDeg}`+'deg)'"></div>
                    </div>
                    <div class="content right">
                      <div class="circle right-circle" :style="'transform:rotate('+`${prodItem.rightDeg}`+'deg)'"></div>
                    </div>
                  </div>
                </template>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <loading-status-tem :dataStatus="loadingStatus" noDataText="暂无课程" class="c-bg-sgray"></loading-status-tem>
      <!-- 全部课程 -->
      <open-modal class="c-pz100" :openModal='showCatalog' @closeModal='closeCatalog'>
        <div class="c-bg-sgray c-p c-br-tl20 c-br-tr20">
          <div @click='closeCatalog' class="c-pa c-p-r0 c-p-t0 c-ph20 c-pv10"><i class="iconfont c-fs30 c-fc-gray">&#xe750;</i></div>
          <div class="c-textAlign-c c-fw500 c-fs28 c-fc-xblack c-pt40 c-pb30">选择展开课程计划</div>
          <ul class="c-liststyle-none c-ph24 catalog-list">
            <li @click="switchPlan(item.planId)" v-for="(item, index) in columnList" :key="index" :class="item.planId == choosePlanId ? 'theme-bg-10 theme-bd2 active':'c-bg-white'">
              <p class="c-fs30 c-fw600 c-fc-xblack">{{item.planName}}</p>
              <p class="c-fc-gray c-fs20 c-mt10">{{item.count}}任务</p>
              <div class="mark c-flex-row c-justify-center c-aligni-center theme-bg"><i class="iconfont c-fs20 c-fc-white c-fw600">&#xe6ea;</i></div>
            </li>
          </ul>
        </div>
      </open-modal>
    </div>
  </infiniteloading>
</template>
<script>
import { utilJs } from "@/utils/common.js";
import { goDetails } from "@/utils/goDetails.js";
import circleUtils from '@/utils/circleUtils.js';
import OpenModal from "@/components/templates/common/openModal.vue";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import infiniteloading from '@/components/templates/livePersonal/infiniteloading/index';
const PAGE_SIZE = 20;
export default {
  name: 'planCourseList',
  components: {
    OpenModal,
    loadingStatusTem,
    infiniteloading
  },
  data() {
    return {
      choosePlanId: 0,
      showCatalog: false,
      showCirclePlanColumn: true,
      planList: [],
      columnList: [],
      planTypeInfo: {},
      planSubInfo: {},
      sortType: 1, //1=正序；2=倒序
      isShowSinglePlan: false, //是否只显示一个
      prodTypes: global.prodMapType,
      loadingStatus:''
    }
  },
  created() {
    this._circleId = this.$route.query.circleId;
    this._page = 1;
    this.getDetails().then(() => {
      this.wechatShare();
      utilJs.appShare(this);
    });
    this._getPlanList().then()
    this._getPlanColumnList();
    this._getPlanTypeInfo().then(() => {
      setDocumentTitle(this.planTypeInfo.coursePlanName);
    });
  },
  methods: {
    loadMoreList() {
      this._page++;
      this._getPlanList();
    },
    // 获取接口数据
    getDetails() {
      return new Promise(resolve => {
        utilJs.getMethod(`${global.apiurl}circle/details/${this._circleId}?type=1`, res => {
          if (res.deletedStatus == -1) {
            this.$routerGo(this, "replace", {
              path: "/error/emptyPage",
              query: {
                from: "circle",
                info: '该圈子已被删除,请联系管理员'
              }
            });
            return
          }
          if (res.isShow == -1) {
            this.$routerGo(this, "replace", {
              path: "/error/emptyPage",
              query: {
                from: "circle",
                info: '该圈子已被隐藏,请联系管理员'
              }
            });
            return
          }
          this._feedTop = res;
          if (!this.isHasPermission(true)) {
            //没有权限
            this.rediretToCircleFeed();
          }
          resolve();
        })
      })
    },
    // 判断是否有权限
    isHasPermission(isShowToast = true) {
      // role：1=成员；2=圈主  status：1=正常；-1=拉入黑名单  isExit:1=正常；-1=退出了圈子
      let toastText = '';
      let flag = true;
      if (this._feedTop.hasPermission == false && this._feedTop.status == 1) {
        toastText = "加入圈子可参与互动";
        flag = false;
      } else if (this._feedTop.hasPermission == false && this._feedTop.status == -1) {
        toastText = "暂无此操作权限，请联系圈子管理员~";
        flag = false;
      } else if (this._feedTop.isExit == -1) {
        toastText = "暂无此操作权限，请联系圈子管理员~";
        flag = false;
      } else if (this._feedTop.status == -1) {
        toastText = "暂无此操作权限，请联系圈子管理员~";
        flag = false;
      }
      if (!flag && isShowToast) {
        this.$showCjToast({
          text: toastText,
          type: "warn",
        });
      }
      return flag;
    },
    //跳转圈子主详情页
    rediretToCircleFeed() {
      this.$routerGo(this, "replace", {
        path: "/homePage/circle/circleFeed",
        query: {
          id: this._circleId
        }
      })
    },
    jumpToDetail(item) {
      console.log(item);
      if (item.relType == 500) {
        this.$routerGo(this, "push", {
          path: "/homePage/circle/circlePlanClockinDetail",
          query: {
            circleId: this._circleId,
            clockinId: item.relId,
          }
        })
      } else {
        let courseType = item.relType == 111 ? 1 : item.relType == 112 ? 2 : 0;
        let prodType = item.relType == 110 || item.relType == 111 || item.relType == 112 ? global.ckFrom.course : item.relType;
        goDetails(this, prodType, item.relId, { circleId: this._circleId, circlePlanId: item.planId }, courseType);
      }
      circleUtils.addPlanMember(this._circleId, item.planId);
    },
    switchPlan(id) {
      this.closeCatalog();
      if (this.choosePlanId == id) {
        this.choosePlanId = 0;
      } else {
        this.choosePlanId = id
      }
      this.planList.forEach(item => {
        if (item.planId == this.choosePlanId) {
          item.isExpand = true;
        } else {
          item.isExpand = false;
        }
      })

      // this._getPlanList(this.choosePlanId);
    },
    toggleSlide(index) {
      this.planList[index].isExpand = !this.planList[index].isExpand;
    },
    switCatalogSort() {
      this.sortType = this.sortType == 1 ? 2 : 1;
      this._page = 1;
      this.planList = [];
      this._getPlanList();
      this._sortPlanColumn();
    },
    _sortPlanColumn() {
      let sortType = this.sortType;
      this.columnList.sort((item1, item2) => {
        if (sortType == 1) {
          // 时间
          return item1.planId - item2.planId;
        } else {
          // 倒序
          return item2.planId - item1.planId;
        }
      })
    },
    _getPlanTypeInfo() {
      return new Promise(resolve => {
        utilJs.getMethod(`${global.apiurl}circle/getPlanSet/${this._circleId}`, res => {
          this.planTypeInfo = res;
          resolve();
        })
      })
    },
    _getPlanColumnList() {
      return new Promise(resolve => {
        utilJs.getMethod(`${global.apiurl}circle/getPlanList/${this._circleId}`, res => {
          this.columnList = res;
          resolve();
        })
      })
    },
    _getPlanList(planId) {
      return new Promise(resolve => {
        this.loadingStatus = 'LOADING';
        let url = `${global.apiurl}circle/getPlanDetailList/${this._circleId}?sortType=${this.sortType}&page=${this._page}&limit=${PAGE_SIZE}`;
        if (planId) {
          url += `&planId=${planId}`;
        }
        utilJs.getMethod(url, res => {
          res.data.forEach(pItem => {
            pItem.isExpand = false;
            pItem.progressPercent = (pItem.progress * 100).toFixed(0);
            pItem.prodlist.forEach(item => {
              let resRatio = circleUtils.calcProgressRatio(item.prodProgress);
              item.leftDeg = resRatio.leftDeg;
              item.rightDeg = resRatio.rightDeg;
              item.planId = pItem.planId
            })
          })
          if (res.data.length && this._page == 1) {
            res.data[0].isExpand = true;
          }
          this.planList = this.planList.concat(res.data);
          if (res.data.length && res.data.length < PAGE_SIZE) {
            this.loadingStatus = 'NO_MORE_DATA';
          } else if (!this.planList.length) {
            this.loadingStatus = 'NO_DATA';
          } else {
            this.loadingStatus = '';
          }
          resolve();
        }, () => {
          this.loadingStatus = '';
        })
      })
    },
    openCatalog() {
      this.showCatalog = true;
    },
    closeCatalog() {
      this.showCatalog = false;
    },
    showCirclePlanColumn() {
      this.showCirclePlanColumn = true;
    },
    //分享
    wechatShare: function () {
      let title = this._feedTop.name || window.localStorage.getItem("shareTitle");
      let shareImg = this._feedTop.avatar || window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/circle/circleFeed?refereeId=${localStorage.getItem("userId")}&id=${this._circleId}`;
      let shareDesc = this._feedTop.shareSetting.shareDesc || this._feedTop.intro || '点击查看详情';
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { }, true);
    },
    //手机端分享
    appShare: function () {
      let title = this._feedTop.name || window.localStorage.getItem("shareTitle");
      let shareImg = this._feedTop.avatar || window.localStorage.getItem("shareLogo");
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/circle/circleFeed?refereeId=${localStorage.getItem("userId")}&id=${this._circleId}`;
      let shareDesc = this._feedTop.shareSetting.shareDesc || this._feedTop.intro || '点击查看详情';
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../../assets/css/scss/circle.scss";
.top-plan-img {
  width: 2.8rem;
  height: 2.8rem;
  margin: 0 0.5rem 0 0;
  background: url("../../../assets/i/wap/circle/plan/course.png") no-repeat top
    center;
  background-size: 100% 100%;
}
.everytask-progress {
  background: #fafafa;
  border-radius: 0.6rem;
  height: 1.2rem;
  padding: 0 0.5rem;
  .lab {
    font-size: 0.5rem;
    color: #999;
    padding: 0 0.5rem 0 0;
    position: relative;
    margin: 0 0.5rem 0 0;
    &:after {
      content: "";
      position: absolute;
      right: 0;
      top: 50%;
      transform: translate(0, -50%);
      width: 0.05rem;
      height: 0.45rem;
      background: #f2f2f2;
    }
  }
  .progress {
    width: 3rem;
    height: 0.2rem;
    background: #e5e5e5;
    border-radius: 0.1rem;
    margin: 0 0.25rem 0 0;
  }
  .percent {
    height: 100%;
    border-radius: 0.1rem;
  }
}

.catalog-list {
  height: 15.25rem;
  overflow-y: scroll;
  li {
    // background: #ffffff;
    border-radius: 0.5rem;
    padding: 0.5rem;
    margin: 0 0 0.6rem 0;
    // border: 2px solid #fff;
    position: relative;
    overflow: hidden;
    &.active {
      // background-color: rgba(255, 113, 0, 0.1);
      // border-color: #ff7100;
      .mark {
        visibility: visible;
      }
    }
  }
  .mark {
    position: absolute;
    right: -2px;
    bottom: -5px;
    border-radius: 0.5rem 0 0 0;
    width: 1rem;
    overflow: hidden;
    height: 1rem;
    visibility: hidden;
  }
}
.arrow-rotate {
  position: relative;
  transition: all 0.5s;
  &.expand {
    transform: rotate(90deg);
    transform-origin: center center;
  }
}
.time-rotate {
  position: relative;
  transition: all 0.5s;
  &.up {
    transform: rotate(180deg);
    transform-origin: center center;
  }
}
</style>